/*
 * @Author: szx
 * @Date: 2023-03-30 13:41:23
 * @LastEditTime: 2023-03-31 18:15:33
 * @Description: 
 * @FilePath: \learn\fullstackopen\part4\controllers\blogs.js
 */
const blogsRouter = require('express').Router()
const Blog = require('../models/blog')

blogsRouter.get('/', async (request, response) => {
    const blogs = await Blog.find({}).populate('user', { username: 1, name: 1 })
    response.json(blogs)
})

blogsRouter.get('/:id', async (request, response) => {
    const blog = await Blog.findById(request.params.id)
    if (blog) response.json(blog)
    else response.status(404).end()
})

blogsRouter.post('/', async (request, response) => {
    const body = request.body

    if (!body.title || !body.url) {
        response.status(400).end();
    } else {
        if (!body.likes) {
            body.likes = 0;
        }
        const user = request.user
        if (!user) return response.status(401).json({ error: 'token is missing or invalid' })

        body.user = user._id
        const savedBlog = await new Blog(body).save();
        user.blogs = user.blogs.concat(savedBlog._id)
        await user.save()

        response.status(201).json(savedBlog)
    }
})

blogsRouter.delete('/:id', async (request, response) => {
    const blog = await Blog.findById(request.params.id);
    if (!blog) return response.status(204).end()

    const user = request.user
    if (blog.user.toString() !== user._id.toString()) {
        return response.status(401).json({ error: 'userid not equal' })
    } else {
        await Blog.findByIdAndRemove(request.params.id)
        return response.status(204).end()
    }
})

blogsRouter.put('/:id', async (request, response) => {
    const body = request.body
    const blog = {
        title: body.title,
        author: body.author,
        url: body.url,
        likes: body.likes || 0
    }

    const updatedBlog = await Blog.findByIdAndUpdate(request.params.id, blog, { new: true }).populate('user', { username: 1, name: 1 })
    return response.json(updatedBlog)

})

module.exports = blogsRouter